﻿var dragGhost = document.createElement("div");
dragGhost.style.border = "dashed 1px #CCCCCC";
dragGhost.style.background = "white";
dragGhost.style.display = "none";
dragGhost.style.margin = "5px";

var isIE = document.all;


var XDrag = new Object();
XDrag.tabs = [];//所有的tab集合 每个元素是tab对象 tab.elm才是html对象
XDrag.pages = []; //所有的页的集合 每个元素是html对象
XDrag.cells = [];
XDrag.selectedTab = null;//当前选中的tab
XDrag.changeTabTimeout = 10;

XDrag.save = function() {//将结果保存到数据库
    var jsonString = new StringBuilder();
    for (var i = 0; i < XDrag.pages.length; i++) {//遍历每一页
        var page = XDrag.pages[i];
        for (var j = 0; j < page.childNodes.length; j++) {//遍历每一列
            var module = page.childNodes[j];
            var module_a = module.getElementsByTagName("a")[0];
            if (module.nodeName.toLowerCase() != "div" || module.style.display == "none")
                continue;
            if (module_a != 'undefined' && module_a != null) {

                jsonString.append('' + module_a.id.substring(1) + "-" + page.id.substring(14) + "-" + (j +1) + ',');
            }
        }
    }
    jsonString.append("]");
    var jsonStr = jsonString.toString();
    var entryids = jsonStr.replace(/,]/g, "");

    $.ajax({
        type: "POST",
        url: "/Ajax/saveEntryOrder",
        data: { entryids: entryids },
        success: function(data, textStatus) {

        }
    });
}
XDrag.readFromCookie = function() {//读取cookie
    var value = getCookie("XDrag") || XDrag.defaultLayout;
    var obj = eval('(' + value + ')');
    return obj;
}

XDrag.init = function() {

    data = XDrag.readFromCookie();

    var clientHeight = document.documentElement.clientHeight - 100;
    //var clientWidth = document.documentElement.clientWidth - 100;
    var clientWidth = 960;

    //var row = parseInt(clientHeight / 50);
    var row = 6;
    var column = parseInt(clientWidth / 120);

    if (document.getElementById("CommonEntries") != "undefined" && document.getElementById("CommonEntries") != null) {

        //$('#entries').css("min-height",clientHeight);
//        var cells = [];
//        var container = document.getElementById("cell-container");


//        column= 840/120;
//        var tempContainer = $("#tempContaniner");
//        var totalcells = 0;
//        if(tempContainer.children().length > row * column)
//        {
//            totalcells = tempContainer.children().length + 10;
//        }
//        else{
//            totalcells = row * column;
//        }
//        totalcells =42;
//        for (var i = 0; i < totalcells; i++) {
//            var cell = document.createElement("div");
//            cell.id = i + 1;
//            cell.className = "cell";
//            container.appendChild(cell);
//            cells.push(cell);
//        }

//        var CommonEntries = document.getElementById("CommonEntries");
//        if (CommonEntries) {
//            var childrenlength = CommonEntries.childNodes.length;
//            for (var i = 0; i < childrenlength; i++) {
//                var item = CommonEntries.getElementsByTagName("div")[0];
//                if(typeof(item) != 'undefined' && typeof(cells[i]) != 'undefined' && item != null && cells[i] != null)
//                {
//                    cells[i].appendChild(item);
//                    item.cell = cells[i];
//                    new dragItem(item);
//                }
//            }
//        }
    }
    else {
        var tabs = document.getElementById("categories").childNodes;
        for (var i = 0; i < tabs.length; i++) {
            if (tabs[i].nodeName.toLowerCase() == "a" && tabs[i].id != "addCategory")
                XDrag.tabs.push(new tab(tabs[i]));
        } //初始化所有的tab页标签

        var pages = document.getElementById("entries");
        for (var i = 0; i < pages.childNodes.length; i++) {
            if (pages.childNodes[i].nodeName.toLowerCase() == "div" && pages.childNodes[i].id.match(/^privateEntries/)) {
                var container = pages.childNodes[i];
                container.cells = [];
                XDrag.pages.push(container);

        
//                for (var j = 0; j <  row * column; j++) {
//                    var cell = document.createElement("div");
//                    cell.id = "cell" + j + 1;
//                    cell.className = "cell";
//                    container.appendChild(cell);
//                    container.cells.push(cell);
//                }
            }
        } //找到所有的页


        var tempContainer = $("#tempContaniner");
        
        for (var i = 0; i < tempContainer.children().length; i++) {
            var moduleElm = tempContainer.children()[0];
            var moduleElm_a = moduleElm.getElementsByTagName("a")[0];
            var categoryId = moduleElm_a.lang.split('-')[0];
            var position = parseInt(moduleElm_a.lang.split('-')[1]);
            moduleElm.page = document.getElementById("privateEntries" + categoryId);
            if (position == 0 || isNaN(position)) {
                var container = $("#privateEntries" + categoryId);
                if(container.children().length == 0)
                {
                    $("#" + moduleElm.id).remove();
                }
                var total = 0;
                for (var j = 0; j < container.children().length; j++) {
                    if (container.children()[j].innerHTML == "") {
                        container.children()[j].appendChild(moduleElm);
                        moduleElm.cell = container.children()[j];
                        new dragItem(moduleElm);
                        total = 0;
                        break;
                    }
                    total = j+1;
                }
                if(total >=container.children().length)
                {
                    var cell = document.createElement("div");
                    cell.id = "cell" + container.children().length + 1;
                    cell.className = "cell";
                    cell.appendChild(moduleElm);
                    moduleElm.cell = cell;
                    document.getElementById(container.attr("id")).appendChild(cell);
                    //container.appendChild(cell);
                    document.getElementById(container.attr("id")).cells.push(cell);
                }
            }
            else {
                if (position >= moduleElm.page.childNodes.length - 1) {
                    for (var j = moduleElm.page.childNodes.length; j <= position; j++) {
                        var cell = document.createElement("div");
                        cell.id = j + 1;
                        cell.className = "cell";
                        moduleElm.page.appendChild(cell);
                        moduleElm.page.cells.push(cell);
                    }
                }
                moduleElm.page.cells[position - 1].appendChild(moduleElm);
                moduleElm.cell = moduleElm.page.cells[position - 1];

                new dragItem(moduleElm);
            }

            i--;
        }

        for (var i = 0; i < XDrag.tabs.length; i++) {
            if (XDrag.pages[i]) {
                var page = XDrag.pages[i]; //page
                XDrag.tabs[i].page = page;
                page.tab = XDrag.tabs[i]; //page和tab可以互相引用

            }
        }
        XDrag.tabs[0].select();
    }
}
var tab = function(tabElm){
	var self = this;
	this.page = null;
	this.elm = tabElm;
	this.select = function(){
		if(!this.page)
			return;
			
	    for(var i=0;i<XDrag.pages.length;i++){
	        XDrag.pages[i].style.display = "none";
	    }
	    
		if(XDrag.selectedTab){
			XDrag.selectedTab.elm.className = "";
			XDrag.selectedTab.page.style.display = "none";
		}
		
		this.elm.className = "current";
		this.page.style.display = "block";
		XDrag.selectedTab = this;
	}
	this.elm.onmouseover = function(){
	    if($("#aEntryAdding") && $("#aEntryAdding").length > 0)//不是查看别人的上网入口时
	    {
	        var setting = "<span id=\"deleteCategoryArea\"><a href=\"#\" id=\"deleteCategory\"><img src=\"Image/Delete21.gif\"  alt=\"删除分类\" title=\"删除分类\"  /></a></span>";
            $("#deleteCategoryArea").remove();
            $("#categories-Container").append(setting);
            var ele = document.getElementById(this.id);
            var rect = ele.getBoundingClientRect();  
            
            $("#deleteCategoryArea").css("position","absolute");
             $("#deleteCategoryArea").css("top",(rect.top-8) + "px");
              $("#deleteCategoryArea").css("left",(rect.left+(parseInt(ele.offsetWidth) - 5)/2) + "px");
            $("#deleteCategory").attr("name",this.id.substring(4));
            rukou.bindDeletePrivateEntryCategoryEvent();
        }
        return false;
	}
	this.elm.onclick = function(){
	    self.select();
		return false;
	}
}


//------------------------Drag Item------------------------
function dragItem(item) {

    var handle = item.childNodes[0].childNodes[0];

    if (!handle) return;
    Drag.init(handle, item);
    item.onDragStart = function(left, top, mouseX, mouseY) {
        //开始拖动的时候设置透明度

        this.style.opacity = "0.5";
        this.style.filter = "alpha(opacity=50)";

        dragGhost.style.height = "25px";
        dragGhost.style.width = "120px";

        //this指的是item

        this.style.width = this.offsetWidth + "px"; //因为初始的width为auto
        var leftpad = (document.documentElement.clientWidth - 960)/2;
        this.style.left = (findPosX(this) + leftpad -5) + "px";
        this.style.top = (findPosY(this) - 5) + "px";
        

        this.style.position = "absolute";
        //将ghost插入到当前位置
        dragGhost.style.display = "block";
        this.cell.insertBefore(dragGhost, this);
    }
    item.onDrag = function(left, top, mouseX, mouseY) {

        var container = item.page;
        if (!container)
            container = document.getElementById("cell-container");

        var leftpad = (document.documentElement.clientWidth - 960)/2;

        var currentNode = null;
        for (var i = 0; i < container.childNodes.length; i++) {
            if (container.childNodes[i].className == "cell"
			&& container.childNodes[i] != this//不能跟拖动元素自己比较 否则不能在本列向下移动
			&& top < findPosY(container.childNodes[i]) + 50
			&& left < findPosX(container.childNodes[i]) + 120 + leftpad) {
                currentNode = container.childNodes[i];
                break;
            }
        }

        if (currentNode && currentNode.childNodes[0]) {
            currentNode.insertBefore(dragGhost, currentNode.childNodes[0]);
            this.cell = currentNode;
        }
        else if (currentNode) {
            currentNode.appendChild(dragGhost);
        }
    }
    item.onDragEnd = function(left, top, mouseX, mouseY) {
        this.style.opacity = "1";
        this.style.filter = "alpha(opacity=100)";

        this.cell.insertBefore(this, dragGhost);

        this.style.position = "static";
        this.style.display = "block";
        this.style.width = "auto";
        dragGhost.style.display = "none";
    }
}


var RunOnBeforeUnload = function(){
	XDrag.save();
}


